<template>
  <el-row>
    <!--    <el-col :span="4">-->
    <!--      <div class="box">-->
    <!--        <el-scrollbar>-->
    <!--          <basic-container>-->
    <!--            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" :defaultExpandAll="true" />-->
    <!--          </basic-container>-->
    <!--        </el-scrollbar>-->
    <!--      </div>-->
    <!--    </el-col>-->
    <el-col :span="24">
      <basic-container>
        <avue-crud :option="option" :table-loading="loading" :data="data" :page="page" :permission="permissionList"
                   :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave"
                   @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange" @size-change="sizeChange" @on-load="onLoad"
                   :upload-error="uploadExceed"
                   v-if="showMain">
          <template slot="menuLeft">
            <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.tz_delete"
                       @click="handleDelete">删 除
            </el-button>
          </template>
          <template slot-scope="{type,size,row,index}" slot="menuBtn">
            <!-- <el-dropdown-item divided @click.native="showZyView(row,index)">编辑资源</el-dropdown-item> -->
            <el-dropdown-item divided @click.native="showQsView(row, index)">签收情况</el-dropdown-item>
          </template>
        </avue-crud>
        <Tzzy v-bind:tzId="tzId" :showMainView="showMainView" v-if="(!showMain) && showzy" ref="eps1"></Tzzy>
        <Tzqs v-bind:tzId="tzId" :showMainView="showMainView" v-if="(!showMain) && showqs" ref="eps2"></Tzqs>
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
//getDetail
import {getList, update, remove, selectImgId, getTreeByTeacherOrStudentSelect} from "@/api/service/tz";
import {mapGetters} from "vuex";


import Tzzy from "@/views/service/tzzy";

import Tzqs from "@/views/service/tzqs";
// import {getXsTree} from "@/api/service/org";
// import { getStore } from "@/util/store";


export default {
  components: {
    Tzzy,
    Tzqs
  },
  data() {
    return {
      types: 0,
      NjId: '0', //年纪id
      SendObjectType: 0,
      treeData: [],
      treeOption: {
        nodeKey: 'id',
        lazy: false,
        addBtn: false,
        menu: false,
        size: 'small',
        defaultExpandAll: true,
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }
      },
      tzId: "",
      showMain: true,
      showzy: false,
      showqs: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      sendObject: [],//下发范围末级id
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: 'menu',
        menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "学校名称",
            prop: "schoolId",
            // search: true,
            // hide: true,
            span: 24,
            rules: [{
              required: true,
              message: "请选择学校",
              trigger: "blur"
            }],
            type: "tree",
            cascader: ['sendObject'],
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            props: {
              label: "xxName",
              value: "id"
            },
            // value: '3',
            // defaultValue:'3'
            change: ({value}) => {
              console.log(value)
              this.form.schoolId = value
              this.getSendObjectData()

            }
          },
          {
            label: "通知标题",
            prop: "title",
            overHidden: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }],
            maxlength: 30,
            showWordLimit: true,
            editDisabled: false
          },
          {
            label: "通知内容",
            prop: "content",
            type: "textarea",
            span: 24,
            minRows: 6,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入通知内容",
              trigger: "blur"
            }],
            maxlength: 800,
            showWordLimit: true,
            editDisabled: false
          },
          {
            label: "发送者",
            prop: "issuedUnit",
            overHidden: true,
            span: 12,
            rules: [{
              required: true,
              message: "请输入下发单位",
              trigger: "blur"
            }],
          },

          {
            label: "通知时间",
            prop: "notificationTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            overHidden: true,
            rules: [{
              required: true,
              message: "请选择通知时间",
              trigger: "blur"
            }],
            editDisabled: true
          },
          {
            label: "通知栏目",
            prop: "sendType",
            overHidden: true,
            rules: [{
              required: true,
              message: "请选择通知栏目",
              trigger: "blur"
            }],
            type: "select",
            dicUrl: "/api/ManageNotification/GetNotificationTypeSelect",
            props: {
              label: "typeName",
              value: "id"
            },
            dataType: "number",
            editDisabled: true
          },
          {
            label: "下发类别",
            // prop: "issuedUnitType",
            prop: "sendObjectType",
            cascader: ['sendObject'],
            overHidden: true,
            clearable:false,
            rules: [{
              required: true,
              message: "请选择下发类别",
              trigger: "blur"
            }],
            type: "select",
            value: 2,
            dicData: [

              {
                // label: "学校",
                label: "教师",
                value: 2
              },
              {
                // label: "年级",
                label: "学生",
                value: 3
              },
              // {
              //   label: "班级",
              //   value: 4
              // },
              // {
              //   label: "教师",
              //   value: 7
              // }
            ],
            dataType: 'number',
            editDisabled: true,
            change: ({value}) => {
              console.log(value)
              this.form.sendObjectType = value
              this.getSendObjectData()

            }
          },
          {
            label: "下发范围",
            prop: "sendObjectName",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: true,
            // span: 24,
            // minRows: 6,
            hide: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入下发范围",
              trigger: "blur"
            }],
            // maxlength: 500,
            // showWordLimit: true,
            // editDisabled: false
          },
          {
            label: "下发范围",
            prop: "sendObject",
            overHidden: true,
            multiple: true,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
            checkStrictly: false,
            rules: [{
              required: true,
              message: "请选择下发范围",
              trigger: "blur"
            }],
            hide: true,
            type: "tree",
            // dicUrl: "/api/ManageNotification/GetTreeByTeacherOrStudentSelect?sendObjectType={{key}}",
            props: {
              label: "title",
              value: "id"
            },
            dicData: [],
            checked: (data, node) => {
              console.log("学生,", node.checkedNodes)
              this.sendObject = []
              if (node.checkedNodes.length > 0) {
                node.checkedNodes.forEach(item => {
                  if (item.hasChildren) {
                    this.sendObject.push(item.id)
                    console.log(item.id, this.sendObject)
                  }
                })
              } else {
                console.log('小于零')
              }
            },
            slot: true,
            editDisabled: true
          },
          {
            label: "附件1",
            prop: "filePath1",
            // props: {label: "name",value: "url",},
            rules: [{
              required: false,
              message: "请上传附件",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            propsHttp: {
              url: 'url',
              name: 'name',
              res: 'data',
            },
            fileSize: 10240,
            action: '/api/localfiles/UploadFileInRecord',
            hide: true
          },
          {
            label: "附件2",
            prop: "filePath2",
            rules: [{
              required: false,
              message: "请上传附件",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            propsHttp: {
              url: 'url',
              name: 'name',
              res: 'data',
            },
            fileSize: 10240,
            action: '/api/localfiles/UploadFileInRecord',
            hide: true
          },
          {
            label: "附件3",
            prop: "filePath3",
            rules: [{
              required: false,
              message: "请上传附件",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            propsHttp: {
              url: 'url',
              name: 'name',
              res: 'data',
            },
            fileSize: 10240,
            action: '/api/localfiles/UploadFileInRecord',
            hide: true
          },
          {
            label: "附件4",
            prop: "filePath4",
            rules: [{
              required: false,
              message: "请上传附件",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            propsHttp: {
              url: 'url',
              name: 'name',
              res: 'data',
            },
            fileSize: 10240,
            action: '/api/localfiles/UploadFileInRecord',
            hide: true
          },
          {
            label: "附件5",
            prop: "filePath5",
            rules: [{
              required: false,
              message: "请上传附件",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            propsHttp: {
              url: 'url',
              name: 'name',
              res: 'data',
            },
            fileSize: 10240,
            action: '/api/localfiles/UploadFileInRecord',
            hide: true
          },


        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission", "JSuserInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tz_add, false),
        viewBtn: this.vaildData(this.permission.tz_view, false),
        delBtn: this.vaildData(this.permission.tz_delete, false),
        editBtn: false,//this.vaildData(this.permission.tz_edit, false)
      };
    },
    js_Id() {
      return this.JSuserInfo.js_Id
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    // var userinfo = getStore({
    //   name: "userInfo",
    // });
    // getBjTree({ jsId: userinfo.relateId }).then(res => {
    //   this.treeData = res.data.data;
    // });
  },
  methods: {
    getSendObjectData() {
      console.log('this.form.schoolId', this.form.schoolId)
      if (this.form.schoolId === '' || this.form.schoolId === undefined || this.form.schoolId === null || this.form.sendObjectType === '' || this.form.sendObjectType === undefined || this.form.sendObjectType === null) {
        return 0
      }
      let params = {
        sendObjectType: this.form.sendObjectType,
        schoolId: this.form.schoolId,
      }
      getTreeByTeacherOrStudentSelect(params).then((res) => {
        const column = this.findObject(this.option.column, "sendObject");
        column.dicData = res.data.data;

      })
    },
    nodeClick(data) {
      this.types = data.type;
      this.NjId = data.value
      this.onLoad(this.page);
    },
    showZyView(row) {
      this.tzId = row.id;
      this.showMain = false;
      this.showzy = true;
      this.showqs = false;
    },
    showQsView(row) {
      this.tzId = row.id;
      this.showMain = false;
      this.showzy = false;
      this.showqs = true;
    },
    showMainView() {
      this.showMain = true;
      this.showzy = false;
      this.showqs = false;
    },
    //新增保存
    //
    rowSave(row, done, loading) {
      console.log(row)
      if (this.sendObject.length <= 0) {
        this.$message({
          type: "warning",
          message: "请选择正确下发范围!"
        });
        loading();
        return 0
      }
      this.$confirm("是否发送通知?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          row.id = "0"
          // row.SendObjectType = this.SendObjectType
          row.fileAttachments = []
          row.sendObject = this.sendObject
          let params = {
            filePath1: row.filePath1.length > 0 ? row.filePath1[0].value : '',
            filePath2: row.filePath2.length > 0 ? row.filePath2[0].value : '',
            filePath3: row.filePath3.length > 0 ? row.filePath3[0].value : '',
            filePath4: row.filePath4.length > 0 ? row.filePath4[0].value : '',
            filePath5: row.filePath5.length > 0 ? row.filePath5[0].value : '',
          }
          selectImgId(params).then((res) => {
            if (res.data.data.filePath1 != null) row.fileAttachments.push(res.data.data.filePath1)
            if (res.data.data.filePath2 != null) row.fileAttachments.push(res.data.data.filePath2)
            if (res.data.data.filePath3 != null) row.fileAttachments.push(res.data.data.filePath3)
            if (res.data.data.filePath4 != null) row.fileAttachments.push(res.data.data.filePath4)
            if (res.data.data.filePath5 != null) row.fileAttachments.push(res.data.data.filePath5)
            this.submit(row, done, loading)
            console.log(row, res.data.filePath1, res.data.data.filePath1)
          })
        })
        .catch(() => {
          loading();
        })


      // row.issuedUnit = this.js_Id + ''
      // row.id = "0"
      // row.SendObjectType = this.SendObjectType
      // row.fileAttachments = []
      // let params = {
      //   filePath1: row.filePath1.length > 0 ? row.filePath1[0].value : '',
      //   filePath2: row.filePath2.length > 0 ? row.filePath2[0].value : '',
      //   filePath3: row.filePath3.length > 0 ? row.filePath3[0].value : '',
      //   filePath4: row.filePath4.length > 0 ? row.filePath4[0].value : '',
      //   filePath5: row.filePath5.length > 0 ? row.filePath5[0].value : '',
      // }
      // selectImgId(params).then((res) => {
      //   if (res.data.data.filePath1 != null) row.fileAttachments.push(res.data.data.filePath1)
      //   if (res.data.data.filePath2 != null) row.fileAttachments.push(res.data.data.filePath2)
      //   if (res.data.data.filePath3 != null) row.fileAttachments.push(res.data.data.filePath3)
      //   if (res.data.data.filePath4 != null) row.fileAttachments.push(res.data.data.filePath4)
      //   if (res.data.data.filePath5 != null) row.fileAttachments.push(res.data.data.filePath5)
      //   this.submit(row, done, loading)
      //   console.log(row, res.data.filePath1, res.data.data.filePath1)
      // })
    },
    submit(row, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    uploadExceed(error) {
      this.$message({
        type: "error",
        message: error
      });
    },
    typenodeClick(data) {
      this.SendObjectType = data.type
    },
    //编辑保存
    // index, done, loading
    rowUpdate(row, index, done, loading) {
      row.fileAttachments = []
      let params = {}
      if (typeof row.filePath1 == 'string') {
        params.filePath1 = row.filePath1 == '' ? '' : row.filePath1
      } else {
        params.filePath1 = row.filePath1.length > 0 ? row.filePath1[0].value : ''
      }
      if (typeof row.filePath2 == 'string') {
        params.filePath2 = row.filePath2 == '' ? '' : row.filePath2
      } else {
        params.filePath2 = row.filePath2.length > 0 ? row.filePath2[0].value : ''
      }
      if (typeof row.filePath3 == 'string') {
        params.filePath3 = row.filePath3 == '' ? '' : row.filePath3
      } else {
        params.filePath3 = row.filePath3.length > 0 ? row.filePath3[0].value : ''
      }
      if (typeof row.filePath4 == 'string') {
        params.filePath4 = row.filePath4 == '' ? '' : row.filePath4
      } else {
        params.filePath4 = row.filePath4.length > 0 ? row.filePath4[0].value : ''
      }
      if (typeof row.filePath5 == 'string') {
        params.filePath5 = row.filePath5 == '' ? '' : row.filePath5
      } else {
        params.filePath5 = row.filePath5.length > 0 ? row.filePath5[0].value : ''
      }
      selectImgId(params).then((res) => {
        if (res.data.data.filePath1 != null) row.fileAttachments.push(res.data.data.filePath1)
        if (res.data.data.filePath2 != null) row.fileAttachments.push(res.data.data.filePath2)
        if (res.data.data.filePath3 != null) row.fileAttachments.push(res.data.data.filePath3)
        if (res.data.data.filePath4 != null) row.fileAttachments.push(res.data.data.filePath4)
        if (res.data.data.filePath5 != null) row.fileAttachments.push(res.data.data.filePath5)
        this.updateSubmit(row, index, done, loading)
        console.log(row, res.data.filePath1, res.data.data.filePath1)
      })
      // update(row).then(() => {
      //   done();
      //   this.onLoad(this.page);
      //   this.$message({
      //     type: "success",
      //     message: "操作成功!"
      //   });
      // }, error => {
      //   window.console.log(error);
      //   loading();
      // });
    },
    updateSubmit(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            ids: row.id + '',
          }
          return remove(data);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            ids: this.ids + '',
          }
          return remove(data);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      console.log(list)
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      // console.log("用户信息",this.$store.getters.JSuserInfo)
      // params.types = this.types; //学校id
      // params.id = this.NjId //年纪id
      getList(page.currentPage, page.pageSize, params).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        let sendObjectNames = []
        if (data.records.length > 0) {
          data.records.forEach(item => {
            if (item.sendObject.length > 0) {
              item.sendObject.forEach(items => {
                console.log('items.name', items.name)
                sendObjectNames.push(items.name)
              })
            }
            console.log('sendObjectNames', sendObjectNames)
            item.sendObjectName = sendObjectNames.toString()
          })
        }
        this.data = data.records;
        console.log(this.data)
        this.loading = false;
        this.selectionClear();
      });

      // getXsTree(this.form.tenantId).then(res => {
      //   const column = this.findObject(this.option.column, "sendObject");
      //   column.dicData = res.data.data;
      // });


    }
  }
};
</script>

<style></style>
